package com.ecplatform.common.handler;

import com.ecplatform.common.constant.MessageConstants;
import com.ecplatform.common.pojo.po.Result;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 在 @ExceptionHandler 方法中，返回 ResponseEntity（包含状态码和响应体），
 * Spring 会直接将其转换为 HTTP 响应并发送给客户端，后续处理链终止。
 */
@RestControllerAdvice
@RequiredArgsConstructor
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handleException(Exception e) {
        // 记录完整的异常堆栈信息
        logger.error("Global exception occurred: ", e); // 这会输出堆栈跟踪

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new Result(500, MessageConstants.ServerError + ": " + e.getMessage(), null));
    }
}
